package com.wh.beans.tags;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;

import com.legend.utils.ReturnResult;
import com.legend.utils.Status;
import com.legend.utils.StringUtils;
import com.wh.beans.ValueText;
import com.wh.model.*;
import com.wh.service.IExt.*;
import com.wh.service.impl.*;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

public class HtmlControls implements TemplateDirectiveModel {
	@Override
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
		String type = params.containsKey("type") ? params.get("type").toString() : "radio";
		String name = params.containsKey("name") ? params.get("name").toString() : "";
		String defValue = params.containsKey("defValue") ? params.get("defValue").toString() : "";
		Integer defIndex = params.containsKey("defIndex") ? Integer.parseInt(params.get("defIndex").toString()) : 1;
		String enumName = params.containsKey("enumName") ? params.get("enumName").toString() : name;
		//Integer width = params.containsKey("width") ? Integer.parseInt(params.get("width").toString()) : 200;
		String panelHeight = params.containsKey("panelHeight") ? params.get("panelHeight").toString() : "200";
        String style=params.containsKey("style")?MessageFormat.format("style=\"{0}\"",params.get("style").toString()):"";
		String classStyle=params.containsKey("class")?params.get("class").toString():"";
        String dataOptions=params.containsKey("dataoptions")?params.get("dataoptions").toString():"";
        HtmlControlType hcType = Enum.valueOf(HtmlControlType.class, type);
		int index = 0;
		StringBuffer s = new StringBuffer();
		ReturnResult result;
		String selected;
		switch (hcType) {
		case radio://以枚举为数据源的radio
			List<ValueText> lst =  SysEnumNameService.getInstance().getEnumCache(enumName);
			for (ValueText vt : lst) {
				index++;
				String checked = "";
				if (defValue == "") {
					checked = defIndex.equals(index) ? "checked" : "";
				} else
					checked = defValue.equalsIgnoreCase(vt.getValue()) ? "checked" : "";
				s.append(MessageFormat.format("<input type='radio' id=rd{0}{1} name={0} value={1} {3}  /> {2} &nbsp;&nbsp;", name, vt.getValue(), vt.getText(), checked));
			}
			env.getOut().write(s.toString());
			break;
		case select://以枚举为数据源的 ｓｅｌｅｃｔ
			String editable = params.containsKey("editable") ? params.get("editable").toString() : "true";
			//lst = new SysEnumNameService().getEnumCache(enumName);
			s = new StringBuffer();
			if (defValue=="") {
				defValue=MessageFormat.format("Enum.{0}[0].value", enumName);
			}
			s.append(MessageFormat.format("<select id=\"sl{0}\" class=\"easyui-combobox {6}\" data-options=\"editable:{1},valueField:\''value\'',textField:\''text\'',data:Enum.{4},value:{5}\" panelHeight=\"{3}\" name=\"{0}\" {2}>", name, editable,style,panelHeight,enumName,defValue,classStyle));
			s.append("</select>");
			env.getOut().write(s.toString());
			break;
		case enumSelect://枚举名
			editable = params.containsKey("editable") ? params.get("editable").toString() : "true";
			ISysEnumNameService enbo =  SysEnumNameService.getInstance();
			List<SysEnumName> enLst = enbo.getEnumNameList(null);
			s = new StringBuffer();
			s.append(MessageFormat.format("<select id=\"sl{0}\" class=\"easyui-combobox {4}\" data-options=\"editable:{1},formatter:formatItem\" panelHeight=\"{3}\" name=\"{0}\" {2}>", name, editable,style,panelHeight,classStyle));
			for (SysEnumName en : enLst) {
				if (defValue == "") {
					selected = defIndex.equals(index) ? "selected" : "";
				} else
					selected = defValue.equalsIgnoreCase(String.valueOf(en.getEnumName())) ? "selected" : "";
				s.append(MessageFormat.format("<option value=\"{0}\"  {1}>{2}</option>", en.getEnumName(), selected,en.getEnumMemo()));
			}
			s.append("</select>");
			env.getOut().write(s.toString());
			break;
		case menuComboTree://菜单
			s.append(MessageFormat.format("<select id=sl{0} name={0} class=\"easyui-combotree {2}\" {1}", name,style,classStyle));
			s.append("data-options=\"required:true\">");
			s.append("</select>");
			ISysMenuService bo =  SysMenuService.getInstance();
			result = bo.getMenuList(true, true, 1);
			s.append(MessageFormat.format("<script type='text/javascript'>var {0}data={1} ;", name, JSONObject.toJSONString(result.getRows())));
			s.append(MessageFormat.format("$(\"#sl{0}\")", name));
			s.append(".combotree({data:");
			s.append(MessageFormat.format("{0}data", name));
			if (!StringUtils.isEmpty(defValue)) {
				s.append(MessageFormat.format(",value:\"{0}\"", defValue));
			}
			s.append("});</script>");
			env.getOut().write(s.toString());
			break;
		case deptComboTree://部门
			s.append(MessageFormat.format("<select id=sl{0} name={0} class=\"easyui-combotree {2}\" {1}", name,style,classStyle));
			s.append("data-options=\"required:true\">");
			s.append("</select>");
			ISysDeptService deptBo =  SysDeptService.getInstance();
			List<SysDept> depts = deptBo.getDeptList(true);
			SimplePropertyPreFilter filter = new SimplePropertyPreFilter("id", "text", "children");

			s.append(MessageFormat.format("<script type='text/javascript'>var {0}data={1} ;", name, JSONObject.toJSONString(depts, filter)));
			s.append(MessageFormat.format("$(\"#sl{0}\")", name));
			s.append(".combotree({data:");
			s.append(MessageFormat.format("{0}data", name));
			if (!StringUtils.isEmpty(defValue)) {
				s.append(MessageFormat.format(",value:\"{0}\"", defValue));
			}

			s.append("});</script>");
			env.getOut().write(s.toString());
			break;
		case roleCombobox://角色
			editable = params.containsKey("editable") ? params.get("editable").toString() : "true";
			ISysRoleService roleBo = SysRoleService.getInstance();
			SysRole entity=new SysRole();
			entity.setStatus(1);
			List<SysRole> roles = roleBo.getList(entity);
			s = new StringBuffer();
			s.append(MessageFormat.format("<select id=\"sl{0}\" class=\"easyui-combobox {4}\" data-options=\"editable:{1}\" panelHeight=\"{3}\" name=\"{0}\" {2}>", name, editable,style,panelHeight,classStyle));
			for (SysRole role : roles) {
				if (defValue == "") {
					selected = defIndex.equals(index) ? "selected" : "";
				} else
					selected = defValue.equalsIgnoreCase(String.valueOf(role.getId())) ? "selected" : "";
				s.append(MessageFormat.format("<option value=\"{0}\" {1}>{2}</option>", role.getId(), selected, role.getRoleName()));
			}
			s.append("</select>");
			env.getOut().write(s.toString());
			break;
            case tableCombobox://表信息
                editable = params.containsKey("editable") ? params.get("editable").toString() : "true";
                IBuilderTableService tableService = BuilderTableService.getInstance();
                BuilderTable BuilderTable=new BuilderTable();
                BuilderTable.setStatus(1);
                result= tableService.selectByModel(BuilderTable);
                if (result.getStatus()== Status.SUCCESS) {
                    List<BuilderTable> tables=(List<BuilderTable>)result.getRows();
                    s = new StringBuffer();
                    s.append(MessageFormat.format("<select id=\"sl{0}\" class=\"easyui-combobox {4}\" data-options=\"{1}\" panelHeight=\"{3}\" name=\"{0}\" {2}>", name, dataOptions, style, panelHeight,classStyle));
                    for (BuilderTable table : tables) {
                        if (defValue == "") {
                            selected = defIndex.equals(index) ? "selected" : "";
                        } else
                            selected = defValue.equalsIgnoreCase(String.valueOf(table.getTableName())) ? "selected" : "";
                        s.append(MessageFormat.format("<option value=\"{0}\" {1}>{2}</option>", table.getTableName(), selected, table.getTableRemark()));
                    }
                    s.append("</select>");
                    env.getOut().write(s.toString());
                }
                break;
            case teamCombobox://团队信息
                IWorkTeamService teamService = WorkTeamService.getInstance();
                WorkTeam workTeam=new WorkTeam();
                workTeam.setStatus(1);
                result= teamService.selectByModel(workTeam);
                if (result.getStatus()== Status.SUCCESS) {
                    List<WorkTeam> tables=(List<WorkTeam>)result.getRows();
                    s = new StringBuffer();
                    s.append(MessageFormat.format("<select id=\"sl{0}\" class=\"easyui-combobox {4}\" data-options=\"{1}\" panelHeight=\"{3}\" name=\"{0}\" {2}>", name, dataOptions, style, panelHeight,classStyle));
                    for (WorkTeam team : tables) {
                        if (defValue == "") {
                            selected = defIndex.equals(index) ? "selected" : "";
                        } else
                            selected = defValue.equalsIgnoreCase(String.valueOf(team.getId())) ? "selected" : "";
                        s.append(MessageFormat.format("<option value=\"{0}\" {1}>{2}</option>", team.getId(), selected, team.getTeamName()));
                    }
                    s.append("</select>");
                    env.getOut().write(s.toString());
                }
                break;
		default:
			break;
		}

	}
}
